// 自定义错误
const { CustomError } = require("./CustomError.js")

// 密钥
const {
  TENCENTCLOUD_APPID,
  TENCENTCLOUD_SECRETID,
  TENCENTCLOUD_SECRETKEY,
} = require("../config.js")


function wx_init(wx){

  wx._personal = {}
  // ========自定义错误=======
  wx._personal.Error = function (res, message, statusCode){
    res = res || 'Forget to define the res'
    message = message || 'Forget to define the message';
    statusCode = statusCode || 0
    return new CustomError(res, message, statusCode)
  }
  // ========配置密钥========
  wx._personal.appId = TENCENTCLOUD_APPID
  wx._personal.secretId = TENCENTCLOUD_SECRETID
  wx._personal.secretKey = TENCENTCLOUD_SECRETKEY

  // ========获取用户openid========
  // 导出一个可以调用的方法 wx._personal.getUserOpenid
  wx._personal.getUserOpenid = getUserOpenid
  wx._personal.openid = null
  getUserOpenid();

  // ========定义弹窗========
  // 1 定义全局loading提示框 
  wx._personal.showLoading = function (title) {
    wx.showLoading({
      title,
      mask: true,
    })
  }
  // 2 定义全局显示消息提示框
  // 2.1 错误消息
  wx._personal.showErrToast = function (title = '网络超时', duration = 2000) {
    wx.showToast({
      title,
      image: "/assets/imgs/error.png",
      mask: true,
      duration,
    })
  }
  // 2.2 正确消息
  wx._personal.showToast = function (title, duration = 2000) {
    wx.showToast({
      title,
      mask: true,
      duration,
    })
  }


  // ========自定义函数========
  // 1 获取用户openid函数 
  function getUserOpenid(){
    wx.cloud.callFunction({
      name: "getOpenid"
    })
      .then(res => {
        // 用户openid为res.result.openid
        wx._personal.openid = res.result.openid
      })
      .catch(res => {
        // 网络超时
        wx._personal.showErrToast()
        throw wx._personal.Error(res, "openid获取失败", 1)
      })
  }

// 
}


// 导出
module.exports = {
  wx_init
}